package znbkBkfx.AboutRecordPlay;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;


import com.lancoo.znbkxx.R;

import java.io.IOException;


/**
 * Incremental change is better than ambitious failure.
 *
 * @author : <a href="http://mysticcoder.coding.me">MysticCoder</a>
 * @date : 2018/3/21
 * @desc : 不用时一定要调用{{@link #release()}}
 */
public class AudioPlayerView extends AppCompatTextView {

    String mUrl ;

    public boolean isHasprepared() {
        return hasprepared;
    }

    /**
     * 在非初始化状态下调用setDataSource  会抛出IllegalStateException异常
     */
    boolean hasprepared =false;

    public MediaPlayer mediaPlayer;

    private Handler handler;
    private Runnable runnable;
    private int i;

    private int[] drawRights = new int[]{R.mipmap.laba1, R.mipmap.laba2,R.mipmap.laba3};

    public AudioPlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);

        initMediaPlayer();
    }
    private void initMediaPlayer(){

        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        } catch (Exception e) {
            Log.e("mediaPlayer", " init error", e);
        }

        if (mediaPlayer != null){
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    Log.e("KKKKMMMM","=============setOnPreparedListener========111111111111=======");
                    hasprepared = true;
//                    setText(getDuration());//屏蔽时间显示
                    Drawable drawableRight = getResources().getDrawable(R.mipmap.laba0);
                    drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),drawableRight.getMinimumHeight());//这一步必须要做,否则不会显示.
                    setCompoundDrawables(null, null, drawableRight, null);

//                    setBackgroundColor(Color.parseColor("#ff0000"));
                }
            });
        }
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.e("KKKKMMMM","=============setOnErrorListener========2222222222222=======");
                mediaPlayer.reset();
                return false;
            }
        });
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.e("KKKKMMMM","=============setOnCompletionListener========333333333333333=======");
                stopAnim();
            }
        });
        setClick();

    }

    public void setUrl(String url){

        mUrl = url;
        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
//            startAnim();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("mediaPlayer", " set dataSource error", e);
        } catch (IllegalStateException e){
            Log.e("mediaPlayer", " set dataSource error", e);
        }
    }

    /**
     * 用于需要设置不同的dataSource
     * 二次setdataSource的时候需要reset 将MediaPlayer恢复到Initialized状态
     * @param url
     */
    public void resetUrl(String url){

        if (TextUtils.isEmpty(mUrl)||hasprepared){
            mediaPlayer.reset();
        }
        setUrl(url);
    }

    public String getDuration(){

        int duration = mediaPlayer.getDuration();

        if (duration == -1){
            return "";
        }else {

            int sec = duration/1000;

            int m = sec/60;
            int s = sec%60;
            return m+":"+s;
        }

    }
    public void startAnim() {

        i = 0;
        if (handler == null) {
            handler = new Handler();
        }
        if (runnable == null) {
            runnable = new Runnable() {
                @Override
                public void run() {

                    handler.postDelayed(this, 300);
                    setDrawableRight(drawRights[i % 3]);
                    i++;
                }
            };
        }

        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 300);
    }

    public void stopAnim(){

//        setDrawableRight(drawRights[2]);
        setDrawableRight(R.mipmap.laba0);
        if (handler != null){
            handler.removeCallbacks(runnable);
        }
    }

    /**
     *  设置 drawableRight
     * @param
     * @param id
     */
    private void setDrawableRight(@DrawableRes int id) {

        Drawable drawableRight = getResources().getDrawable(id);
        drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(),drawableRight.getMinimumHeight());//这一步必须要做,否则不会显示.

//        Drawable rightDrawable = getResources().getDrawable(id);
//        rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
        setCompoundDrawables(null, null, drawableRight, null);

    }

    private void setClick(){

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

//                第一次调用start播放正常. 然后调用stop().停止播放.然后再调start 放不了

//
                //方案一： 先stop，再Reset ，stop换成pause也行
//                if (mediaPlayer.isPlaying()){
//                    mediaPlayer.stop();
//                    stopAnim();
//                }else {
//                    mediaPlayer.reset();
//                    setUrl(mUrl);
//                    startAnim();
//                    mediaPlayer.start();
//
//                }

                // 采取方案二  pause  代替 stop
                if (mediaPlayer.isPlaying()){
                    Log.e("setClick","==================暂停播放============");
                    mediaPlayer.pause();
                    stopAnim();
                }else {
                    Log.e("setClick","===================开启播放===========");
                    mediaPlayer.seekTo(0);
                    startAnim();
                    mediaPlayer.start();
                }

            }

        });
    }

    /**
     * 释放资源
     */
    public  void release() {
        if ( mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }

        if (handler != null){
            handler.removeCallbacks(runnable);
        }
    }

}